import { loginApi, getUserInfo } from "@/api/login";
import { setItem, getItem, removeAllItem } from "@/utils/storage";
import { TOKEN } from "@/constant";
import router from "@/router";

export default {
  namespaced: true, // 表示是一个单独的模块
  state: () => ({
    token: getItem(TOKEN) || "",
    userInfo: {},
    // 侧边栏宽度
    asideWidth: "250px",
  }),
  mutations: {
    setToken(state, token) {
      state.token = token;
      setItem("token", token);
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setAsideWidth(state) {
      state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px";
    },
  },
  actions: {
    //  context 是 Vuex 自动传递给每个 action 的第一个参数。它的作用是提供对 Vuex 模块内部和全局状态管理功能的访问。
    loginAction(context, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        loginApi(username, password)
          .then((data) => {
            this.commit("user/setToken", data.token);
            resolve();
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 退出功能
    logoutAction() {
      this.commit("user/setToken", "");
      this.commit("user/setUserInfo", {});
      removeAllItem();
      // TODO：清理权限相关配置
      router.push("/login");
    },
    // 获取用户信息
    async userInfoAction(context) {
      const res = await getUserInfo();
      this.commit("user/setUserInfo", res.data);
      return res;
    },
  },
};
